package com.softserveinc.lahire.handlers;

import java.io.IOException;

import com.softserveinc.lahire.builders.Request;

/**
 * 
 * Class, that manage chain of handlers.
 * Used to build-up and store a chain of handlers.
 * Provide single point of access to handle() method 
 * 
 * @author Pavlo Lozovskiy
 * 
 */

public class HandlersChain {
	private Handler root = null;

	public HandlersChain() {
		
		addHandler(new AdminHandler());
		addHandler(new DirectoryHandler());
		addHandler(new TextHandler());
		addHandler(new BinaryHandler());

	}

	public Handler getRoot() {
		return root;
	}

	private Handler addHandler(Handler handler) {
		Handler next;
		if (root == null) {
			root = handler;
		} else if (root.getParent() == null) {
			root.setParent(handler);
		} else {
			next = root.getParent();

			while (next.getParent() != null) {
				next = next.getParent();
			}
			next.setParent(handler);

		}
		return handler;
	}

	public void handle(Handler handler, Request request) {
		byte[] body = null;
		
		try {
			handler.handle(request);
		} catch (IOException e) {
			System.out.println("File cannot be found");
		}
		
		//return body;
	}
}
